package ch.fusun.baron.turn;

import java.util.Timer;
import java.util.TimerTask;

import ch.fusun.baron.data.AbstractDataProvider;
import ch.fusun.baron.data.DataListener;
import ch.fusun.baron.data.DataUpdate;
import ch.fusun.baron.data.EmptyUpdate;

/**
 * THe implementation of the turn service
 */
public class TurnServiceImpl extends AbstractDataProvider implements
		TurnService {

	private transient boolean started = false;

	@Override
	public void start(int delay) {
		synchronized (this) {
			if (!started) {
				Timer timer = new Timer();
				timer.scheduleAtFixedRate(new TimerTask() {

					@Override
					public void run() {
						for (DataListener turnListener : getListeners()) {
							if (turnListener instanceof TurnListener) {
								((TurnListener) turnListener).onTurn();
							} else {
								turnListener.dataChanged(new EmptyUpdate());
							}
						}
					}
				}, delay, delay);
				started = true;
			}
		}
	}

	@Override
	public DataUpdate createFullUpdate() {
		return new EmptyUpdate();
	}

}
